package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.DiyStrategy;
import com.ruoyi.system.domain.TbDiyStrategyPro;
import com.ruoyi.system.domain.vo.ExcutePythonVo;
import com.ruoyi.system.domain.vo.HigistPriceVo;
import com.ruoyi.system.domain.vo.RoeVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TbDiyStrategy;
import com.ruoyi.system.service.ITbDiyStrategyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 策略生成Controller
 * 
 * @author ruoyi
 * @date 2022-02-16
 */
@RestController
@RequestMapping("/system/strategy")
public class TbDiyStrategyController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(TbDiyStrategyController.class);
    @Autowired
    private ITbDiyStrategyService tbDiyStrategyService;
    private static String STY_index(Map<String, Object> map){
        return map.get("STY_index").toString();
    }
    private static String trans_dt(Map<String, Object> map){
        return map.get("trans_dt").toString();
    }
    private static String HS300_index(Map<String,Object> map) {return map.get("HS300_index").toString();}


    /**
     * 查询策略生成列表
     */
    @PreAuthorize("@ss.hasPermi('system:strategy:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbDiyStrategy tbDiyStrategy)
    {
        startPage();
        List<TbDiyStrategy> list = tbDiyStrategyService.selectTbDiyStrategyList(tbDiyStrategy);
        return getDataTable(list);
    }

    /**
     * 导出策略生成列表
     */
    @PreAuthorize("@ss.hasPermi('system:strategy:export')")
    @Log(title = "策略生成", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbDiyStrategy tbDiyStrategy)
    {
        List<TbDiyStrategy> list = tbDiyStrategyService.selectTbDiyStrategyList(tbDiyStrategy);
        ExcelUtil<TbDiyStrategy> util = new ExcelUtil<TbDiyStrategy>(TbDiyStrategy.class);
        util.exportExcel(response, list, "策略生成数据");
    }

    /**
     * 策略执行
     */
    @Log(title = "策略执行", businessType = BusinessType.OTHER)
    @PutMapping ("/executePython")
    public AjaxResult executePython(@RequestBody ExcutePythonVo excutePythonVo)
    {
//        String s = tbDiyStrategyService.executePython(tbDiyStrategy);
        return AjaxResult.success(tbDiyStrategyService.executePython(excutePythonVo));

    }

    /**
     * 获取策略生成详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:strategy:query')")
    @GetMapping(value = "/{strategyCd}")
    public AjaxResult getInfo(@PathVariable("strategyCd") String strategyCd)
    {
        return AjaxResult.success(tbDiyStrategyService.selectTbDiyStrategyByStrategyNm(strategyCd));
    }

    /**
     * 新增策略生成
     */
    @PreAuthorize("@ss.hasPermi('system:strategy:add')")
    @Log(title = "策略生成", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbDiyStrategy tbDiyStrategy)
    {
        return toAjax(tbDiyStrategyService.insertTbDiyStrategy(tbDiyStrategy));
    }

    /**
     * 修改策略生成
     */
    @PreAuthorize("@ss.hasPermi('system:strategy:edit')")
    @Log(title = "策略生成", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbDiyStrategy tbDiyStrategy)
    {
        return AjaxResult.success(tbDiyStrategyService.updateTbDiyStrategy(tbDiyStrategy));
    }

    /**
     * 删除策略生成
     */
    @PreAuthorize("@ss.hasPermi('system:strategy:remove')")
    @Log(title = "策略生成", businessType = BusinessType.DELETE)
	@DeleteMapping("/{strategyCds}")
    public AjaxResult remove(@PathVariable String[] strategyCds)
    {
        return toAjax(tbDiyStrategyService.deleteTbDiyStrategyByStrategyNm(strategyCds[0]));
    }

    /**
     * 剔除重复因子
     */
    @Log(title = "策略生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteitem")
    public AjaxResult deleteitem()
    {
        return toAjax(tbDiyStrategyService.deleteitem());
    }

    /**
     * 导出形态选股样本集列表
     */
    @Log(title = "形态选股样本集", businessType = BusinessType.EXPORT)
    @GetMapping ("/exportOne/{strategyCd}")
    @ResponseBody
    public void exportOne(HttpServletResponse response, @PathVariable("strategyCd")String strategyCd)
    {
        TbDiyStrategyPro tbDiyStrategyPro= tbDiyStrategyService.selectTbDiyStrategyProByStrategyNm(strategyCd.split("_")[0]);
//        ExcelUtil<TbShapeSampleSet> util = new ExcelUtil<TbShapeSampleSet>(TbShapeSampleSet.class);
//        List<TbShapeSampleSet> list=new ArrayList<>();
//        list.add(tbShapeSampleSet);

        try {

            String path = File.separator + "data2"+File.separator+"pythondata"+File.separator+"fb_stock_calc_hw"+File.separator+"excel_out" + File.separator;
//            String path=File.separator + "data2" + File.separator + "fubaMaintainWeb" + File.separator +"downloadPath" + File.separator;
            String srcfilename = tbDiyStrategyPro.getExcelPath();
            System.out.println(srcfilename);

            String srcSimplefilename = path +   "kline_sim.xlsm";
            String dirfilename =   "kline_sim_"+tbDiyStrategyPro.getStrategyCd() + ".xlsm";
//            File f = new File(filenam);
//            InputStream input =  new FileInputStream(f);
//            ExcelUtil<TbStrategySet> util = new ExcelUtil<TbStrategySet>(TbStrategySet.class);
//            List<TbStrategySet> list = util.importExcel(input);
            ExcelUtil<TbDiyStrategyPro> util = new ExcelUtil<TbDiyStrategyPro>(TbDiyStrategyPro.class);
            util.mergeExcel(response,srcfilename,  srcSimplefilename,dirfilename);
        }
        catch (Exception e)
        {
            e.printStackTrace();
//            return AjaxResult.error("系统错误，请联系管理员！");
        }

    }

    /**
     * 解析excel数据
     */
    @Log(title = "解析excel数据", businessType = BusinessType.OTHER)
    @GetMapping ("/importData/{strategyCd}")
    @ResponseBody
    public AjaxResult importData(HttpServletResponse response, @PathVariable("strategyCd")String strategyCd)
    {
        TbDiyStrategyPro tbDiyStrategyPro= tbDiyStrategyService.selectTbDiyStrategyProByStrategyNm(strategyCd);

        try {

            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            String srcfilename = tbDiyStrategyPro.getExcelPath();
            System.out.println(srcfilename);
            /**。。。。。。。。。。。。。。。。。。。。。。测试excel 文件读取转化为list。。。。。。。。。。。。。。。。。。。。。。。。。。。。**/
            ExcelUtil<HigistPriceVo> higistPriceVoExcelUtil = new ExcelUtil<>(HigistPriceVo.class);
            File srcexcelFile = new File(srcfilename);
            if (!srcexcelFile.exists()) {
                log.error("指定的Excel文件不存在！");
//                throw new FileException("指定的Excel文件不存在，请联系网站管理员！");
            }
            FileInputStream inputStream = new FileInputStream(srcexcelFile);
            Workbook sheets = WorkbookFactory.create(inputStream);
            Map<String,Object> datas = higistPriceVoExcelUtil.importExcelForMap( null,sheets, 0);
            Map<String,Object> tbDiyStrategyPros = higistPriceVoExcelUtil.importExcelForMap("投资评价", sheets, 0);
            Map<String,Object> ROEs = higistPriceVoExcelUtil.importExcelForMap("收益率", sheets, 0);
//            Map<String,Object> userStocks = higistPriceVoExcelUtil.importExcelForMap("持股票池", sheets, 0);
            ArrayList<Map<String,Object>> RorDataList = (ArrayList<Map<String,Object>>) ROEs.get("dataList");
            ArrayList<Map<String,Object>> tbDiyStrategyProsList = (ArrayList<Map<String,Object>>) tbDiyStrategyPros.get("dataList");



            List<String> trans_dt = RorDataList.stream().map(TbDiyStrategyController::trans_dt).collect(Collectors.toList());
            List<String> STY_index = RorDataList.stream().map(TbDiyStrategyController::STY_index).collect(Collectors.toList());
            List<String> HS300_index = RorDataList.stream().map(TbDiyStrategyController::HS300_index).collect(Collectors.toList());
            List<Map<String,Object>> rlist = tbDiyStrategyProsList.stream().filter(o -> (!"".equals(o.get("Ra")) || !"".equals(o.get("Rh")) || !"".equals(o.get("Rm"))|| !"".equals(o.get("R3a"))|| !"".equals(o.get("Wa"))|| !"".equals(o.get("Wm"))
                    || !"".equals(o.get("W3a")) || !"".equals(o.get("SRa"))|| !"".equals(o.get("SRm"))|| !"".equals(o.get("SR3a"))|| !"".equals(o.get("IRa"))|| !"".equals(o.get("IRm"))|| !"".equals(o.get("IR3a")))).collect(Collectors.toList());
            tbDiyStrategyPros.put("dataList",rlist);
            objectObjectHashMap.put("datas",datas);
            objectObjectHashMap.put("tbDiyStrategyPros",tbDiyStrategyPros);
//            objectObjectHashMap.put("ROEs",ROEs);
//            objectObjectHashMap.put("userStocks",userStocks);
            objectObjectHashMap.put("trans_dt",trans_dt);
            objectObjectHashMap.put("STY_index",STY_index);

            ArrayList<String> list=new ArrayList<>();
            for(int i=0;i<HS300_index.size();i++){
                if(i==0){
                    list.add("0");
                }else {
                    list.add(String.format("%.2f",(Double.valueOf(HS300_index.get(i))-Double.valueOf(HS300_index.get(0)))/Double.valueOf(HS300_index.get(0))));
                }
            }
            objectObjectHashMap.put("HS300_index",list);
            return AjaxResult.success(objectObjectHashMap);
            /**。。。。。。。。。。。。。。。。。。。。。。测试excel 文件读取转化为list。。。。。。。。。。。。。。。。。。。。。。。。。。。。**/
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return AjaxResult.error("系统错误，请联系管理员！");
        }

    }


}
